#!/usr/bin/env node

const fs = require('fs')
const path = require('path')
const inquirer = require('inquirer')
const ejs = require('ejs')
const { exec } = require('child_process')

inquirer.prompt([{
  type: 'input',
  name: 'name',
  message: 'Project Name:'
}, {
  type: 'input',
  name: 'author',
  message: 'Author:'
}, {
  type: 'confirm',
  name: 'react',
  message: 'Whether to install react'
}, {
  type: 'list',
  message: 'License:',
  name: 'license',
  choices: [
    "ISC",
    "MIT",
  ],
  filter: function (val) {
    return val.toLowerCase()
  }
}])
.then(answer => {
  const temDir = path.join(__dirname, 'templates')
  const destDir = process.cwd()

  fs.readdir(temDir, (err, files) => {
    if (err) throw err
    files.forEach(file => {
      ejs.renderFile(path.join(temDir, file), answer, (errs, res) => {
        if (errs) throw errs

        fs.writeFileSync(path.join(destDir, file), res)
      })
    })

    console.log('initializing……')
    if (answer.react) {
      console.log('installing react……')
      exec('npm install react -S', (err) => { if (err) throw err })
    }
  })
})